from flask import Flask, render_template, request, url_for, flash, redirect  # 引入flask包中的Flask类
import sqlite3  # 导入sqlite3

app = Flask(__name__, template_folder='../templates', static_folder='../static')  # 创建一个Flask对象
app.config['SECRET_KEY'] = 'Zeeker-pier will be a good Geek, hahaha'


def get_db_conn():
    """
    获取数据库连接

    返回:
        conn: SQLite数据库连接对象
    """
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row  # 从database.db获取出来的每一条数据都可以当成字典
    return conn


def get_post(post_id):
    """
    根据ID获取文章

    参数:
        post_id (int): 文章ID

    返回:
        post (dict): 文章数据字典，如果没有找到则返回None
    """
    conn = get_db_conn()
    post = conn.execute('SELECT * FROM posts WHERE id = ?', (post_id,)).fetchone()
    return post


@app.route('/')  # 如果请求根目录URL，就访问下面的hello方法
def index():
    """
    首页视图函数

    返回:
        render_template('index.html', posts=posts): 渲染文章列表模板
    """
    conn = get_db_conn()
    posts = conn.execute("select * from posts order by created desc").fetchall()
    return render_template('index.html', posts=posts)


@app.route('/posts/<int:post_id>')  # 表示后面的这些内容可变,会把post_id传给post()
def post(post_id):
    """
    文章详情视图函数

    参数:
        post_id (int): 文章ID

    返回:
        render_template('post.html', post=post): 渲染文章详情模板
    """
    post = get_post(post_id)
    return render_template('post.html', post=post)


@app.route('/posts/new', methods=['GET', 'POST'])
def new():
    """
    新建文章视图函数

    返回:
        render_template('new.html'): 渲染新建文章模板
        redirect(url_for('index')): 重定向到首页
    """
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']

        if not title:
            flash('标题不能为空')
        elif not content:
            flash('内容不能为空')
        else:
            conn = get_db_conn()
            conn.execute('INSERT INTO posts (title, content) VALUES (?, ?)',
                         (title, content))
            conn.commit()
            conn.close()
            flash('文章保存成功！')
            return redirect(url_for('index'))  # 重定向这个玩意
    return render_template('new.html')


@app.route('/posts/<int:post_id>/edit', methods=['GET', 'POST'])
def edit(post_id):
    """
    编辑文章视图函数

    参数:
        post_id (int): 文章ID

    返回:
        render_template('edit.html', post=post): 渲染编辑文章模板
        redirect(url_for('post', post_id=post_id)): 重定向到文章详情页
    """
    post = get_post(post_id)

    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        print(content)
        if not title:
            flash('标题不能为空!')

        elif not content:
            flash('内容不能为空!')

        else:
            conn = get_db_conn()
            conn.execute('UPDATE posts SET title = ? ,content = ? WHERE id = ?',
                         (title, content, post_id))
            conn.commit()  # 提交
            conn.close()  # 关闭
            return redirect(url_for('post', post_id=post_id))
    return render_template('edit.html', post=post)


@app.route('/posts/<int:post_id>/delete', methods=['GET', 'POST'])
def delete(post_id):
    """
    删除文章视图函数
    参数:
        post_id (int): 文章ID
    返回:
        redirect(url_for('index')): 重定向到首页
    """
    post = get_post(post_id)
    conn = get_db_conn()
    conn.execute('DELETE FROM posts WHERE id =?', (post_id,))
    conn.commit()
    conn.close()
    flash('"{} 删除成功'.format(post['title']))
    return redirect(url_for('index'))


@app.route('/posts/about')
def about():
    return render_template('about.html')
